﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Reviewer.Business;
using Reviewer.Entities.Services;
using Reviewer.Entities;
using System.IO;

public partial class CMSV2_Controls_News_NewsInfo : System.Web.UI.UserControl
{
    public Guid NewsId
    {
        get
        {
            if (!String.IsNullOrEmpty(Request["NewsId"]))
            {
                return new Guid(Request["NewsId"]);
            }
            return Guid.Empty;
        }
    }

    public void Refresh()
    {
        if (this.NewsId != Guid.Empty)
        {
            using (INewsService service = ServiceFactory.NewsService)
            {
                News item = service.GetByNewsId(this.NewsId).FirstOrDefault();
                if (item != null && item.Id > 0)
                {
                    this.uiTxtTitle.Text = item.Title;
                    this.uiTxtDescription.Text = item.Header;
                    this.uiTxtText.Text = item.Text;
                    this.uiDdlType.SelectedValue = item.NewsType.ToString();
                    this.uiTxtSource.Text = item.Source;
                    this.uiCbShowRelatedScreenshotsInText.Checked = item.ShowRelatedScreenshots;

                    uiBtnDelete.Enabled = true;

                    BindGameFormats();
                    NewsFormat[] formats = service.GetAssociatedGameFormats(item.NewsId);
                    foreach (ListItem litem in this.uiCblGameFormats.Items)
                    {
                        if (formats.FirstOrDefault(t => t.FormatId.Equals(int.Parse(litem.Value))) != null)
                        {
                            litem.Selected = true;
                        }
                        else
                        {
                            litem.Selected = false;
                        }
                    }
                }
            }
        }
    }

    public void Clear()
    {
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindNewsTypes();
            BindGameFormats();
        }
    }

    private void BindNewsTypes()
    {
        using (IMetadataService<NewsType> service = ServiceFactory.GetMetadataService<NewsType>())
        {
            this.uiDdlType.DataSource = service.GetAll();
            this.uiDdlType.DataTextField = "Name";
            this.uiDdlType.DataValueField = "Id";
            this.uiDdlType.DataBind();
        }
    }

    private void BindGameFormats()
    {
        if (this.uiCblGameFormats.Items.Count == 0)
        {
            using (IMetadataService<Format> service = ServiceFactory.GetMetadataService<Format>())
            {
                uiCblGameFormats.DataSource = service.GetAll().OrderBy(t => t.Name);
                uiCblGameFormats.DataTextField = "Name";
                uiCblGameFormats.DataValueField = "Id";
                uiCblGameFormats.DataBind();
            }
        }
    }

    protected void uiBtnDelete_Click(object sender, EventArgs e)
    {
        if (!this.NewsId.Equals(Guid.Empty))
        {
            using (INewsAdminService adminService = ServiceFactory.NewsAdminService)
            {
                string filename = ResolveUrl("~/news/" + NewsId.ToString() + ".");
                if (File.Exists(MapPath(filename + "png")))
                {
                    File.Delete(MapPath(filename + "png"));
                }
                else if (File.Exists(MapPath(filename + "jpg")))
                {
                    File.Delete(MapPath(filename + "jpg"));
                }

                adminService.DeleteByNewsId(this.NewsId);
            }

            UriHandler.ClearNewsDirectory();

            Response.Redirect("NewsList.aspx");
        }
    }

    protected void uiBtnSave_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            using (INewsAdminService adminService = ServiceFactory.NewsAdminService)
            using (INewsService service = ServiceFactory.NewsService)
            {
                News newsInstance = null;
                bool isNewInstance = false;

                if (this.NewsId != null && !this.NewsId.Equals(Guid.Empty))
                {
                    newsInstance = service.GetByNewsId(this.NewsId).FirstOrDefault();
                }
                else
                {
                    newsInstance = new News();
                    isNewInstance = true;
                }

                newsInstance.Title = uiTxtTitle.Text;
                newsInstance.NewsType = int.Parse(uiDdlType.SelectedValue);
                newsInstance.Header = uiTxtDescription.Text.Length > 255 ? uiTxtDescription.Text.Substring(0, 255) : uiTxtDescription.Text;
                newsInstance.Text = uiTxtText.Text;
                newsInstance.Source = uiTxtSource.Text;
                newsInstance.ShowRelatedScreenshots = uiCbShowRelatedScreenshotsInText.Checked;

                newsInstance = adminService.Save(newsInstance);

                List<NewsFormat> formats = new List<NewsFormat>();
                foreach (ListItem item in this.uiCblGameFormats.Items)
                {
                    if (item.Selected)
                    {
                        NewsFormat format = new NewsFormat();
                        format.FormatId = int.Parse(item.Value);
                        format.NewsId = newsInstance.NewsId;
                        formats.Add(format);
                    }
                }
                adminService.SetAssociatedGameFormats(this.NewsId, formats.ToArray());

                if (isNewInstance)
                {
                    UriHandler.ClearNewsDirectory();
                }

                Response.Redirect("NewsManager.aspx?NewsId=" + newsInstance.NewsId.ToString(), true);
            }
        }
    }

    protected void uiCvTitle_ServerValidate(object source, ServerValidateEventArgs args)
    {
        string normalizedTitle = UrlUtillity.NormalizeString(args.Value).ToUpperInvariant();
        KeyValuePair<string, Guid> item = UriHandler.NewsDictionary.FirstOrDefault(t => t.Key.ToUpperInvariant().Equals(normalizedTitle, StringComparison.Ordinal));
        if (String.IsNullOrEmpty(item.Key))
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = item.Value.Equals(this.NewsId);
        }
    }
}
